package com.ph.website.home.base.conf;

import com.ph.website.home.base.component.GlobalParam;
import com.ph.website.home.base.interceptor.AuthInterceptor;
import com.ph.website.home.base.interceptor.LoggerInterceptor;
import com.ph.website.home.base.utils.SystemUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Bean
    public LoggerInterceptor loggerInterceptor(){
        return new LoggerInterceptor();
    }

    @Bean
    public AuthInterceptor authInterceptor(){
        return new AuthInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        /**日志记录,优先级0*/
        //拦截的url
        List<String> logPatterns = new ArrayList<>();
        logPatterns.add("/api/**");

        registry.addInterceptor(loggerInterceptor())
                .order(0)
                .addPathPatterns(logPatterns);


        /**token校验,优先级1*/
        //拦截的url
        List<String> authPatterns = new ArrayList<>();
        authPatterns.add("/api/**");
        //过滤的url
        List<String> authExcludePatterns = new ArrayList<>();
        authExcludePatterns.add("/api/member/login");

        registry.addInterceptor(authInterceptor())
                .order(1)
                .addPathPatterns(authPatterns)
                .excludePathPatterns(authExcludePatterns);
    }



    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        setImgParam();
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:" + globalParam.getImg().getImgLocation());
    }

    @Value("${home.param.img.upload-path}")
    private String uploadPath;

    @Resource
    private GlobalParam globalParam;

    //设置图片相关参数
    private void setImgParam() {

        GlobalParam.ImgParam img = globalParam.getImg();
        if(img==null){
            img = new GlobalParam.ImgParam();
            globalParam.setImg(img);
        }

        //以jar包的方式启动
        if(SystemUtil.runWithJar()){

            String location = SystemUtil.jarLocation()+"/upload/";
            img.setStartJar(1);
            img.setImgLocation(location);
            img.setPrefix("");
        }

        //不是以jar包的方式启动.开发时前后端分离
        else{
            img.setStartJar(0);
            img.setImgLocation(uploadPath);
        }

        File file = new File(img.getImgLocation());
        if(!file.exists()){
            file.mkdirs();
        }

    }
}
